<template>
  <common-edit-dialog
    :visible="dialogShow"
    :title="dialogTitle"
    :button-loading="loading"
    width="800px"
    @cancel="close"
    @submit="submitForm"
  >
    <el-form ref="form" :model="form" :rules="rules" label-width="80px" @submit.native.prevent>
      <el-row :gutter="18">
        <el-col :span="24">
          <el-form-item label="权限名称" prop="permissionName">
            <common-input
              v-model="form.permissionName"
              :maxlength="16"
              :type="'text'"
              placeholder="请输入"
            />
          </el-form-item>
        </el-col>
        <!--        <el-col :span="12">-->
        <!--          <el-form-item label="状态" prop="status">-->
        <!--            <el-radio v-model="form.status" label="0">正常</el-radio>-->
        <!--            <el-radio v-model="form.status" label="1">停用</el-radio>-->
        <!--          </el-form-item>-->
        <!--        </el-col>-->

        <!--        <el-col :span="24">-->
        <!--          <el-form-item label="数据权限">-->

        <!--            <el-checkbox v-model="dataExpand" @change="handleCheckedTreeExpand($event, 'dataSource')">展开/折叠-->
        <!--            </el-checkbox>-->
        <!--            <el-checkbox v-model="dataNodeAll" @change="handleCheckedTreeNodeAll($event, 'dataSource')">全选/全不选-->
        <!--            </el-checkbox>-->
        <!--            <div class="form-box mt10">-->
        <!--              <el-tree class="tree-border" :data="dataSourceOptions" show-checkbox ref="dataSource" node-key="id"-->
        <!--                       :check-strictly="checkStrictly" :default-checked-keys="dataSourceIds" empty-text="加载中，请稍后"-->
        <!--                       :props="dataSourceProp"></el-tree>-->
        <!--            </div>-->
        <!--          </el-form-item>-->
        <!--        </el-col>-->

        <el-col :span="24">
          <el-form-item label="数据权限" prop="deptIds">
            <el-checkbox
              v-model="menuExpand"
              @change="handleCheckedTreeExpand($event)"
            >展开/折叠
            </el-checkbox
            >
            <el-checkbox
              v-model="menuNodeAll"
              @change="handleCheckedTreeNodeAll($event)"
            >全选/全不选
            </el-checkbox
            >
            <div class="form-box mt10">
              <el-tree
                class="tree-border"
                :data="deptList"
                ref="depTree"
                node-key="id"
                show-checkbox
                :default-checked-keys="form.deptIds"
                check-strictly
                empty-text="暂无数据"
                @check-change="checkChange"
                :props="roleTreeProps"
              >
              </el-tree>
              <!-- <el-tree
                class="tree-border"
                :data="roleList"
                show-checkbox
                how-checkbox
                ref="roleTree"
                node-key="id"
                :default-checked-keys="form.roleIds"
                :check-strictly="checkStrictly"
                empty-text="暂无数据"
                :props="roleTreeProps"
              >
              </el-tree> -->
            </div>
          </el-form-item>
        </el-col>
        <!--        <el-col :span="24">-->
        <!--          <el-form-item label="组织权限">-->
        <!--            <el-checkbox v-model="deptExpand" @change="handleCheckedTreeExpand($event, 'dept')">展开/折叠</el-checkbox>-->
        <!--            <el-checkbox v-model="deptNodeAll" @change="handleCheckedTreeNodeAll($event, 'dept')">全选/全不选</el-checkbox>-->
        <!--            <div class="form-box mt10">-->
        <!--              <el-tree class="tree-border" :data="deptOptions" show-checkbox ref="dept" node-key="id"-->
        <!--                       :default-checked-keys="form.deptIds" :check-strictly="true" empty-text="加载中，请稍后"-->
        <!--                       :props="deptProps"></el-tree>-->
        <!--            </div>-->
        <!--          </el-form-item>-->
        <!--        </el-col>-->

        <el-col :span="24">
          <el-form-item label="备注">
            <common-input
              type="textarea"
              :autosize="{ minRows: 4, maxRows: 8 }"
              v-model="form.remark"
              placeholder="请输入"
            />
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
  </common-edit-dialog>
</template>

<script>
  import '@riophae/vue-treeselect/dist/vue-treeselect.css'
  import {
    getRoleTree,
    getDeptTree,
    authAdd,
    getAuthInfo,
    authEdit,
    getDeptTreeForPermissionForAdd,
    getDeptTreeForPermissionForEdit,
    getRoleTreeForEdit,
    getRoleTreeForAdd
  } from '@/api/management/usercenter/user.js'

  export default {
    name: 'authAdd',
    data() {
      const checkContent = (rule, value, callback) => {
        if (value && value.length === 0 && this.form.roleIds.length === 0) {
          callback(new Error('请选择组织或角色'))
        } else {
          callback()
        }
      }
      return {
        form: {
          permissionName: '',
          deptIds: [],
          roleIds: [],
          status: '0',
          delFlag: '0',
          remark: ''
        },
        rules: {
          permissionName: [
            { required: true, message: '请输入权限名称', trigger: 'blur' }
          ],
          deptIds: [
            { required: true, validator: checkContent, trigger: 'blur' }
            // {
            //   required: true,
            //   message: '请输入权限名称',
            //   trigger: 'blur'
            // }
          ]
        }, //检验
        dialogShow: false, //显示隐藏
        loading: false,
        dialogTitle: null, //弹窗标题
        menuExpand: false, //是否展开
        menuNodeAll: false, //是否全选
        roleList: [], //角色列表
        checkStrictly: false,
        roleTreeProps: {
          children: 'children',
          label: 'label',
          disabled: 'disabled'
        },
        deptList: []
      }
    },
    methods: {
      /**
       * 显示
       */
      show(data) {
        this.dialogTitle = data.permissionId ? '编辑权限' : '新增权限'
        this.dialogShow = true
        this.form = data.permissionId ? data : this.$options.data().form

        if (!!data.permissionId) {
          this.isGetInfo(true)
        } else {
          this.isGetInfo()
        }
      },
      isGetInfo(isGetInfo) {
        Promise.all([
          isGetInfo ? this.getRoleTreeForEdit() : this.getRoleTreeForAdd(),
          isGetInfo ? this.getDeptTreeForPermissionForEdit() : this.getDeptTreeForPermissionForAdd(),
          isGetInfo ? this.getAuthInfo(this.form.permissionId) : null
        ]).then((res) => {
          this.roleList.push({
            ...res[0],
            disabled: !res[0].children || !res[0].children.length
          })
          this.deptList.push({
            label: '组织',
            id: '0',
            children: res[1].depts
          })
          let changeData = (data) => {
            data.forEach((f) => {
              f.disabled = f.freeze !== 'N'
              if (f.children && f.children.length > 0) {
                changeData(f.children)
              }
            })
          }
          changeData(this.deptList)
          if (isGetInfo) {
            this.$nextTick(() => {
              this.form = res[2]
              if (this.form.deptIds) {
                this.changeTreeNodeStatus(this.deptList, 'depTree', true)
              }
              if (this.form.roleIds) {
                this.changeTreeNodeStatus(this.roleList, 'roleTree', true)
              }
            })
          }
        })
      },
      /**
       * 提交
       */
      submitForm() {
        // let roleIds = this.$refs.roleTree.getCheckedKeys()
        // this.roleList.forEach((f) => {
        //   this.form.roleIds = roleIds.length
        //     ? roleIds.filter((v) => v !== f.id)
        //     : []
        // })
        this.$refs['form'].validate((valid) => {
          if (valid) {
            this.loading = true
            if (!this.form.permissionId) {
              authAdd(this.form)
                .then((res) => {
                  if (res && res.code === 200) {
                    this.$GlobalSuccessMessage('新增成功')
                    this.close()
                    this.$emit('refresh')
                  } else {
                    this.$GlobalErrorConfirm('新增失败', res.msg).then()
                  }
                })
                .finally(() => (this.loading = false))
            } else {
              authEdit(this.form)
                .then((res) => {
                  if (res && res.code === 200) {
                    this.$GlobalSuccessMessage('编辑成功')
                    this.close()
                    this.$emit('refresh')
                  } else {
                    this.$GlobalErrorConfirm('编辑失败', res.msg).then()
                  }
                })
                .finally(() => (this.loading = false))
            }
          }
        })
      },
      /**
       * 关闭
       */
      close() {
        this.form = {
          permissionName: '',
          deptIds: [],
          roleIds: [],
          status: '0',
          delFlag: '0',
          remark: ''
        }
        this.menuExpand = false
        this.menuNodeAll = false
        this.dialogShow = false
      },
      /**
       * 展开/隐藏
       */
      handleCheckedTreeExpand(value) {
        this.$nextTick(() => {
          this.changeTreeNodeStatus(this.deptList, 'depTree', value)
          this.changeTreeNodeStatus(this.roleList, 'roleTree', value)
        })
      },
      /**
       * 改变树展开收起状态
       */
      changeTreeNodeStatus(node, ref, value) {
        for (let i = 0; i < node.length; i++) {
          this.$refs[ref].store.nodesMap[node[i].id].expanded = value
          if (node[i].children && node[i].children.length > 0) {
            this.changeTreeNodeStatus(node[i].children, ref, value)
          }
        }
      },
      /**
       * 全选/取消全选
       */
      handleCheckedTreeNodeAll(value) {
        this.$refs.depTree.setCheckedNodes(value ? this.deptList : [])
        this.$refs.roleTree.setCheckedNodes(value ? this.roleList : [])
      },
      /**
       * 获取角色列表(新增)
       */
      getRoleTreeForEdit() {
        return new Promise((resolv, reject) => {
          this.roleList = []
          getRoleTreeForEdit().then((res) => {
            if (res && res.code === 200) {
              resolv(res.data)
            } else {
              reject()
              this.roleList = []
            }
          }).catch((err) => {
            reject()
            this.roleList = []
          })
        })
      },
      /**
       * 获取角色列表(编辑)
       */
      getRoleTreeForAdd() {
        return new Promise((resolv, reject) => {
          this.roleList = []
          getRoleTreeForAdd().then((res) => {
            if (res && res.code === 200) {
              resolv(res.data)
            } else {
              reject()
              this.roleList = []
            }
          }).catch((err) => {
            reject()
            this.roleList = []
          })
        })
      },
      /**
       * 获取部门列表(新增)
       */
      getDeptTreeForPermissionForAdd() {
        return new Promise((resolv, reject) => {
          this.deptList = []
          getDeptTreeForPermissionForAdd().then((res) => {
            if (res && res.code === 200) {
              resolv(res.data)
            } else {
              reject()
              this.deptList = []
            }
          }).catch((err) => {
            reject()
            this.deptList = []
          })
        })
      },
      /**
       * 获取部门列表(编辑)
       */
      getDeptTreeForPermissionForEdit() {
        return new Promise((resolv, reject) => {
          this.deptList = []
          getDeptTreeForPermissionForEdit().then((res) => {
            if (res && res.code === 200) {
              resolv(res.data)
            } else {
              reject()
              this.deptList = []
            }
          }).catch((err) => {
            reject()
            this.deptList = []
          })
        })
      },
      checkChange(val, isTrue) {
        if (val.children && val.children.length > 0) {
          let setChecked = (data) => {
            data.forEach((f) => {
              this.$refs.depTree.setChecked(f.id, isTrue, true)
              if (f.children && f.children.length > 0) {
                setChecked(f.children)
              }
            })
          }
          setChecked(val.children)
        }
        this.form.deptIds = this.$refs.depTree.getCheckedKeys()
      },
      /**
       * 根据id获取数据
       */
      getAuthInfo(id) {
        return new Promise((resolv, reject) => {
          getAuthInfo({ permissionId: id })
            .then((res) => {
              if (res && res.code === 200) {
                resolv(res.data)
              } else {
                reject()
                this.$GlobalErrorConfirm(
                  '获取信息失败',
                  res.msg,
                  '重新加载'
                ).then(() => {
                  this.getAuthInfo(id)
                })
              }
            })
            .catch((err) => {
              reject()
              this.$GlobalErrorConfirm('获取信息失败', err.msg, '重新加载').then(
                () => {
                  this.getAuthInfo(id)
                }
              )
            })
        })
      }
    },
    mounted() {
    }
  }
</script>

<style lang="scss" scoped>
  .form-box {
    border: 1px solid #dcdfe6;
    padding: 15px;
    border-radius: 4px;
    max-height: 240px;
    overflow-y: scroll;
  }
</style>
